<template>
  <div class="container">
    <div id="bj">
      <van-nav-bar
        class="bj"
        title="注册"
        left-text=""
        right-text="登录"
        left-arrow
        @click-left="$router.back()"
        @click-right="onClickRight"
      ></van-nav-bar>
    </div>

    <div class="form">
      <van-form
        class="form"
        colon
        :show-error="false"
        :show-error-message="false"
        :validate-first="true"
        @submit="onSubmit"
        @failed="onFailed"
      >
        <van-field name="uploader" label="点击上传头像">
          <template #input style="border-radius: 50%">
            <van-uploader v-model="fileList" multiple :max-count="1" :deletable="false" :after-read="onRead" />
          </template>
        </van-field>
        <van-field
          v-model="name"
          label="用户名"
          left-icon="user-circle-o"
          placeholder="请输入用户名"
          type="text"
          name="name"
          :rules="formRules.uname"
        />
        <van-field
          v-model="pwd"
          clearable
          label="密码"
          left-icon="edit"
          placeholder="请输入密码"
          type="password"
          name="pwd"
          :rules="formRules.pwd"
        />
        <van-field
          v-model="repwd"
          clearable
          label="确认密码"
          left-icon="edit"
          placeholder="请再次输入密码"
          name="repwd"
          type="password"
          :rules="formRules.repwd"
        />
        <div class="reg-btn-wrap">
          <van-button native-type="submit" class="reg-btn" type="info" block>快速注册</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>


<script>
import { Toast } from "vant";

export default {
  data() {
    return {
      fileList: [],
      avatar: '',
      name:'',
      pwd:'',
      repwd:'',
      formRules: {
        uname: [
          { required: true, message: "请输入正确用户名" },
          { pattern: /^[0-9a-zA-Z\u4E00-\u9FA5\_]{2,16}$/, message: "用户名格式错误" },
        ],
        code: [
          { required: true, message: "请填写正确密码" },
          { pattern: /^[a-z0-9_-]{6,18}$/, message: "密码格式错误" },
        ],
        recode: [
          { required: true, message: "请再次填写密码" },
          { pattern: /^[a-z0-9_-]{6,18}$/, message: "密码格式错误" },
        ],
      },
    };
  },
  methods: {
    // 头像上传
    onRead (file) {
      console.log(file)
      let formData = new FormData()
      formData.append('avatar', file.file)
      console.log(formData)
      this.axios.post('/upload', formData, {
        headers: {
          'enctype': 'multipart/form-data'
        }
      }).then(res => {
        console.log(res.data)
        this.fileList[0]=res.data.path//
      })
    },
    onSubmit(values){
      if(this.pwd !== this.repwd){
        this.$toast({
            message:'两次密码输入不一致',
            position:'bottom',
            duration:2000
          })
      }else{
        console.log('表单验证通过，执行注册...',values)
      // 发送注册请求
      let url = "/register"
      console.log(this.fileList[0])
      let params = `name=${this.name}&password=${this.pwd}&repassword=${this.repwd}&avatar=${this.fileList[0]}`
      this.axios.post(url,params).then(res =>{
        console.log('注册',res)
        if(res.data.code==200){
          // 注册成功
          this.$toast({
            message:'注册成功',
            position:'bottom',
            duration:2000
          })
          this.$router.push('/login')
        }else if(res.data.code==201){
          // 注册失败，用户已存在
          this.$toast({
            message:'用户名已存在，换个试试',
            position:'bottom',
            duration:2000
          })
        }
      })
      }
    },
    onClickRight() {
      this.$router.push("/login");
    },
    // async afterRead(file) {
    //   console.log(file)
    //   // 此时可以自行将文件上传至服务器
    //   // const fromData = new fromData
    //   // formdata.append('avatar',file.file)
    //   // const res = await this.axios.post('/register',formData)
    //   // console.log(res)
    // },
    async onRegister() {
      Toast.loading({
        message: "注册中...",
        forbidClick: true,
      });
    },
    onFailed(error) {
      console.log("验证失败", error);
      if (error.errors[0]) {
        this.$toast({ message: error.errors[0].message, position: "top" });
      }
    },
  },
};
</script>


<style lang="css" scoped>
body {
  background-color: #f5f7f9;
}

.container .bj {
  background-color: #034fbe;
}
.container .bj ::v-deep .van-nav-bar__title {
  color: #fff;
}
.container .bj ::v-deep .van-nav-bar__text {
  color: #fff;
}
.container .bj ::v-deep .van-nav-bar__arrow {
  color: #fff;
}

.container .form .tx {
  border-radius: 50%;
}

.container .reg-btn-wrap {
  padding: 26px 16px;
  background-color: #fff;
}
.container .reg-btn-wrap .reg-btn {
  background-color: #6db4fb;
  border: none;
  border-radius: 18px;
}
.container .reg-btn-wrap .reg-btn .van-button__text {
  font-size: 15px;
}
</style>
